package com.shop.admincontroller;

import com.shop.entity.SysUser;
import com.shop.service.SysUserService;
import com.shop.utils.ResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
@Slf4j
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    /**
     * 查询所有用户
     * @return ResultUtils
     */
    @ApiOperation("查询所有用户")
    @RequiresRoles(value = {"admin"})
    @GetMapping("/listUsers")
    public ResultUtils listUsers(@ApiParam(value = "用户名") @RequestParam(required = false)  String userName,
                                 @ApiParam(value = "当前页数") @RequestParam(required = false)Integer current,
                                 @ApiParam(value = "每页显示多少条") @RequestParam(required = false) Integer size){
        ResultUtils allSysUser = sysUserService.findUserRoleByNameData(userName,current,size);
        return allSysUser;
    }

    /**
     * 修改用户信息
     * @param sysUser
     * @return ResultUtils
     */
    @ApiOperation("修改用户信息")
    @RequiresRoles(value = {"admin"})
    @GetMapping("/updateSysUser")
    public ResultUtils updateSysUser(SysUser sysUser,@RequestParam(value = "roleId",required = false) List<Integer> roleId){
        return  sysUserService.updateSysUser(sysUser,roleId);
    }

    /**
     * 用户登录
     * @param user
     * @return  ResultUtils
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public ResultUtils login(@RequestBody  SysUser user) {
        return  sysUserService.login(user);
    }


    /**
     * 退出登录
     * @return  ResultUtils
     */
    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public ResultUtils logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return  ResultUtils.ok();
    }

    /**
     * 根据id删除用户
     * @return  ResultUtils
     */
    @ApiOperation("根据id删除用户数据和授予角色")
    @RequiresRoles(value = {"admin"})
    @PostMapping("/deleteUserById")
    public ResultUtils deleteUserByid(Integer id) {
        ResultUtils resultUtils = sysUserService.deleteSysUserById(id);
        return  resultUtils;
    }

    /**
     * 新增用户
     * @return  ResultUtils
     */
    @ApiOperation("新增用户授予角色")
    @RequiresRoles(value = {"admin"})
    @PostMapping("/saveUser")
    public ResultUtils saveUser(SysUser user,Integer roleId) {
        ResultUtils resultUtils = sysUserService.saveSysUser(user,roleId);
        return  resultUtils;
    }

}
